/****************************************************
	文件：ResMgr.cs
	作者：HuskyT
	邮箱：1005240602@qq.com
	日期：2020/9/27 20:37:5
	功能：资源管理器
*****************************************************/

using System;
using UnityEngine;
using HTUtility;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections.Generic;

namespace HTFramework.ResKit
{
    public class ResMgr : Singleton<ResMgr>
    {
        public void Init()
        {
            ResRecorder.Instance.Init();
            LoadABConfig();
            HTLogger.Info("ResMgr init done.");
        }

        private void LoadABConfig()
        {
            //1.加载 ABConfig
            string cfgABPath = ResUtil.GetABFullPath(FConsts.CONFIG_ABNAME);//Path.Combine(Application.streamingAssetsPath, Consts.CONFIG_ABNAME);
            HTLogger.Debug("AB包配置表的AB包资源路径：" + cfgABPath);
            AssetBundle cfgAB = AssetBundle.LoadFromFile(cfgABPath);
            TextAsset textAsset = cfgAB.LoadAsset<TextAsset>(FConsts.CONFIG_ASSET_NAME);
            if (textAsset == null)
            {
                HTLogger.Error("LoadABConfig error ! AB包配置表（{0}）不存在，\n路径：{1}", FConsts.CONFIG_ASSET_NAME, cfgABPath);
            }
            MemoryStream memoryStream = new MemoryStream(textAsset.bytes);
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            AssetBundleConfig cfg = (AssetBundleConfig)binaryFormatter.Deserialize(memoryStream);
            memoryStream.Close();

            List<string> abNameLst = new List<string>();
            //2.缓存 ResItem
            for (int i = 0; i < cfg.ABDataList.Count; i++)
            {
                ABData abData = cfg.ABDataList[i];
                ResItem resItem = new ResItem();
                resItem.Crc = abData.Crc; //资源路径对应的Crc
                resItem.Path = abData.Path;
                resItem.AssetName = abData.AssetName;
                resItem.ABName = abData.ABName;
                resItem.ABDependencyList = abData.ABDependencyList;
                resItem.RecorderType = ResRecorderType.UNLOADED;

                //缓存所有的 ABName
                if (abNameLst.Contains(abData.ABName) == false)
                {
                    abNameLst.Add(abData.ABName);
                }
                foreach (string item in abData.ABDependencyList)
                {
                    if (abNameLst.Contains(item) == false)
                    {
                        abNameLst.Add(item);
                    }
                }
            }
            //3.缓存 ABItem
            foreach (string abName in abNameLst)
            {
                ABItem abItem = new ABItem();
                abItem.ABName = abName;
                abItem.Crc = CRC32.GetCrc32(abName);
                abItem.RecorderType = ResRecorderType.UNLOADED;
            }
            HTLogger.Info("AB包配置表加载、缓存完成！共计{0}个 ResItem , {1}个 ABItem", cfg.ABDataList.Count, abNameLst.Count);
        }
    }
}
